import { useUserInfoStore } from '@/stores/userInfo'
import axios, { type AxiosRequestHeaders, type AxiosResponse } from 'axios'
import { ElMessage } from 'element-plus'

// 后端返回的响应数据的接口
interface ReqResponseData<T> {
  success: boolean
  code: number
  message: string
  data: T
}

const request = axios.create({
  baseURL: import.meta.env.VITE_API_URL,
  timeout: 50000
})

request.interceptors.request.use(
  (config) => {
    const token = useUserInfoStore().token
    if (token) {
      ;(config.headers as AxiosRequestHeaders).token = token
    }
    return config
  },
  (error) => {
    return Promise.reject(error)
  }
)

request.interceptors.response.use(
  (response: AxiosResponse<ReqResponseData<any>>) => {
    if (response.data.code === 20000 || response.data.code === 200) {
      return response.data.data
    } else {
      ElMessage.error(response.data.message)
      return Promise.reject(response)
    }
  },
  (error) => {
    ElMessage.error('ajax请求失败' + error.message)
    return Promise.reject(error)
  }
)

export default request
